{extend name="$admin_layout" /}
{block name="style"}
<style>
#table2 td{font-size:8px}
</style>
{/block}
{block name="content"}

<div class="panel panel-default">
  <div style="padding:10px">
	  <div class="alert alert-warning">
		  如果导入的数据出现科学计数法，请先在EXcel中将其格式设置为常规  然后另存为xlsx文件即可<br />
	  </div>
	  <a href="" class="btn btn-danger btn-file">
		导入表格
		<input type="file" id="excel-file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" >
	  </a>  
  </div>
	<div class="panel-heading">导入预览</div>
	<div class="panel-body table-responsive">
		<table class="table table-bordered" id="table2">
			<thead><tr></tr></thead><tbody></tbody>	
		</table>
	</div>
	<div class="panel-body">
		<a href="javascript:void(0);" class="btn btn-success" id="import">确定导入</a>
	</div>

</div>

{/block}
{block name="script"}
<script src="/static/admin/js/xlsx.core.min.js"></script>
<script>
var regix = {
	year : /^\d{4}$/,
	month : /\d{1,2}/,
	idcard : /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
	money:  /^(\d+|\d+\.\d{1,2})$/
};
var fields = {
	'order_sn':{'type':"text","name":"订单号","require":0,"regix":false,"width":50},
	'express_no':{'type':"text","name":"发货单号","require":0,"regix":false,"width":50},
	'express_company_id':{'number':"text","name":"快递公司id","require":0,"regix":false,"width":50},
	'express_company':{'type':"text","name":"快递公司","require":0,"regix":false,"width":50},
};
Object.keys(fields).forEach(function(index) {
	var _self = fields[index];
	var width =  _self.width ? 'width="'+_self.width+'px"' : "";

	var td = $('<td '+width+'>'+_self.name+'</td>');
	$("#table2 thead tr").append(td)
});
var td = $('<td >检测</td>');
$("#table2 thead tr").append(td)

function filterObj(obj){
	var ouput = {};
	Object.keys(fields).forEach(function(index) {
		ouput[index] = obj[index] || "";
	});
	return ouput;
}

function checkInfo(ouput){
	try{
		Object.keys(ouput).forEach(function(index) {
			var _self = fields[index];	
			if(_self.require && ! ouput[index]){
				throw new Error( _self.name +"必须填写");
			}
			if(ouput[index]){
				if(_self.regix && ! _self.regix.test(ouput[index])){
					throw new Error( _self.name +"格式不正确");
				}
				if(_self.type == "number" && ! /^\d+$/.test(ouput[index])){
					throw new Error(_self.name +"只能是整数");
				}
			}
		});
	}catch(e){
		return e.message;
	}
	return true;
}
var newArr = [];

 $(function() {
    Stars.init()
	//给input标签绑定change事件，一上传选中的.xls文件就会触发该函数
    $('#excel-file').change(function(e) {
        var files = e.target.files;
        var fileReader = new FileReader();
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result
                var workbook = XLSX.read(data, {
                    type: 'binary'
                }) // 以二进制流方式读取得到整份excel表格对象
                var persons = []; // 存储获取到的数据
            } catch (e) {
                console.log('文件类型不正确');
                return;
            }
            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];
                    console.log(fromTo);
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    break; // 如果只取第一张表，就取消注释这行
                }
            }
			
			persons.forEach(function(item,index){
				if(index > 0){
					var msg = "";
					var obj = filterObj(item);
					var msg = checkInfo(obj);
					if(true === msg){
						newArr.push(obj);
					}
				   
					var tr = "";
					Object.keys(obj).forEach(function(index) {
						tr += '<td>'+ obj[index] +'</td>';
					});
					tr += '<td><font color="red">'+ msg +'</font></td>';
					$("#table2 tbody").append('<tr>'  + tr + '</tr>')
				}			
			})
            //在控制台打印出来表格中的数据
            console.log('ok',newArr);
        };
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(files[0]);
    });
	$("#import").click(function(){
		if(newArr.length < 1){
			layer.msg("没有可导入的数据")
			return;
		}
		$.post("{:url('do_edit_import')}",{dataInfo:JSON.stringify(newArr)},function(result){
			 layer.msg(result.msg)
		     setTimeout(function(){
                if (self != top) {
                　　parent.window.location.reload();
                }else{
                    window.location.reload();
                }

			 },2000)
		},"json")
	})
 })
 
</script>
{/block}